<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>中英文翻翻乐</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: Arial, sans-serif;
            background-color: #f0f2f5;
            display: flex;
            flex-direction: column;
            align-items: center;
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 800px;
            width: 100%;
            padding: 0 10px;
        }

        .header {
            text-align: center;
            margin-bottom: 30px;
        }

        .mode-selection {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 15px;
            margin-bottom: 20px;
        }

        .mode-card {
            background: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            cursor: pointer;
            transition: transform 0.2s;
            text-align: center;
        }

        .mode-card:hover {
            transform: translateY(-5px);
        }

        .game-container {
            display: none;
            background: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }

        .game-info {
            display: flex;
            justify-content: space-between;
            margin-bottom: 20px;
        }

        .card-grid {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 8px;
            width: 100%;
        }

        .card {
            aspect-ratio: 1;
            background: #4a90e2;
            border-radius: 5px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 16px;
            color: white;
            cursor: pointer;
            transition: all 0.3s;
            user-select: none;
            -webkit-tap-highlight-color: transparent;
            touch-action: manipulation;
            position: relative;
            overflow: hidden;
        }

        .card:active {
            transform: scale(0.95);
        }

        .card.flipped {
            background: #82c0ff;
        }

        .card.matched {
            background: #52c41a;
        }

        .custom-mode {
            display: none;
            margin-top: 20px;
        }

        .custom-mode textarea {
            width: 100%;
            height: 100px;
            margin-bottom: 10px;
            padding: 10px;
            border: 1px solid #d9d9d9;
            border-radius: 5px;
            resize: vertical;
        }

        button {
            background: #1890ff;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
        }

        button:hover {
            background: #40a9ff;
        }

        .pairs-selector {
            margin-bottom: 15px;
        }

        select {
            padding: 5px;
            border-radius: 5px;
            border: 1px solid #d9d9d9;
            margin-left: 10px;
        }

        @media (max-width: 480px) {
            .container {
                padding: 0 5px;
            }

            .header h1 {
                font-size: 24px;
            }

            .mode-card {
                padding: 15px 10px;
            }

            .mode-card h2 {
                font-size: 18px;
            }

            .game-info {
                font-size: 14px;
                flex-wrap: wrap;
                gap: 10px;
                justify-content: center;
            }

            .card-grid {
                grid-template-columns: repeat(4, 1fr);
                gap: 5px;
            }

            .card {
                font-size: 12px;
                padding: 5px;
            }

            button {
                padding: 8px 16px;
                font-size: 14px;
            }

            .pairs-selector {
                text-align: center;
                font-size: 14px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>中英文翻翻乐</h1>
            <p>选择游戏模式开始玩吧！</p>
        </div>

        <div class="mode-selection">
            <div class="mode-card" data-mode="fruits">
                <h2>水果模式</h2>
                <p>学习常见水果的中英文</p>
            </div>
            <div class="mode-card" data-mode="animals">
                <h2>动物模式</h2>
                <p>学习常见动物的中英文</p>
            </div>
            <div class="mode-card" data-mode="custom">
                <h2>自定义模式</h2>
                <p>创建自己的词语对</p>
            </div>
        </div>

        <div class="custom-mode">
            <p>请输入中英文对应（每行一对，用空格分隔）：</p>
            <textarea placeholder="例如：
苹果 apple
香蕉 banana"></textarea>
            <button id="startCustomGame">开始游戏</button>
        </div>

        <div class="game-container">
            <div class="pairs-selector">
                词对数量：
                <select id="pairCount">
                </select>
            </div>
            <div class="game-info">
                <div>当前模式：<span id="currentMode">-</span></div>
                <div>时间：<span id="timer">0</span>秒</div>
                <div>配对：<span id="matches">0</span>/<span id="totalPairs">6</span></div>
                <div>最快记录：<span id="bestTime">-</span>秒</div>
            </div>
            <div class="card-grid"></div>
            <button id="restartGame" style="margin-top: 20px;">重新开始</button>
        </div>
    </div>

    <script src="./config.js"></script>
    <script>

        // 游戏记录数据
        const gameRecords = {
            bestTimes: {}
        };

        let gameTimer;
        let seconds = 0;
        let matches = 0;
        let flippedCards = [];
        let currentMode = null;
        let currentPairs = [];

        // 获取DOM元素
        const modeCards = document.querySelectorAll('.mode-card');
        const customMode = document.querySelector('.custom-mode');
        const gameContainer = document.querySelector('.game-container');
        const cardGrid = document.querySelector('.card-grid');
        const timerDisplay = document.getElementById('timer');
        const matchesDisplay = document.getElementById('matches');
        const startCustomGameBtn = document.getElementById('startCustomGame');
        const restartGameBtn = document.getElementById('restartGame');
        const customTextarea = document.querySelector('.custom-mode textarea');
        const pairCountSelect = document.getElementById('pairCount');

        // 加载保存的记录
        function loadRecords() {
            const savedRecords = localStorage.getItem('gameRecords');
            if (savedRecords) {
                const parsed = JSON.parse(savedRecords);
                Object.assign(gameRecords.bestTimes, parsed.bestTimes);
            }
        }

        // 更新最快通关时间
        function updateBestTime(mode, time) {
            const pairCount = parseInt(pairCountSelect.value);
            const key = `${mode}_${pairCount}`;
            if (!gameRecords.bestTimes[key] || time < gameRecords.bestTimes[key]) {
                gameRecords.bestTimes[key] = time;
                localStorage.setItem('gameRecords', JSON.stringify(gameRecords));
                return true;
            }
            return false;
        }

        // 获取指定模式的最快通关时间
        function getBestTime(mode) {
            const pairCount = parseInt(pairCountSelect.value);
            const key = `${mode}_${pairCount}`;
            return gameRecords.bestTimes[key] || Infinity;
        }

        // 加载自定义词对
        function loadCustomWords() {
            const savedWords = localStorage.getItem('customWords');
            if (savedWords) {
                gameConfig.wordPairs.custom = JSON.parse(savedWords);
            }
        }

        // 添加自定义词对
        function addCustomPairs(pairs) {
            gameConfig.wordPairs.custom = pairs;
            localStorage.setItem('customWords', JSON.stringify(pairs));
        }

        // 获取自定义词对
        function getCustomPairs() {
            return gameConfig.wordPairs.custom || [];
        }

        // 更新词对数量选择器选项
        function updatePairCountOptions(mode) {
            const pairs = mode === 'custom' ? getCustomPairs() : gameConfig.wordPairs[mode];
            const maxPairs = pairs.length;
            const select = document.getElementById('pairCount');
            select.innerHTML = '';
            
            for (let i = 4; i <= maxPairs; i += 2) {
                const option = document.createElement('option');
                option.value = i;
                option.textContent = i + '对';
                if (i === 6) option.selected = true;
                select.appendChild(option);
            }
        }

        // 添加模式选择事件监听器
        modeCards.forEach(card => {
            card.addEventListener('click', () => {
                const mode = card.dataset.mode;
                updatePairCountOptions(mode);
                if (mode === 'custom') {
                    showCustomMode();
                } else {
                    startGame(mode);
                }
            });
        });

        // 显示自定义模式输入界面
        function showCustomMode() {
            customMode.style.display = 'block';
            gameContainer.style.display = 'none';
        }

        // 开始游戏
        function startGame(mode, customPairs = null) {
            currentMode = mode;
            const pairCount = parseInt(pairCountSelect.value);
            
            if (mode === 'custom') {
                currentPairs = customPairs || getCustomPairs();
            } else {
                currentPairs = gameConfig.wordPairs[mode].slice(0, pairCount);
            }
            
            // 更新总配对数显示
            document.getElementById('totalPairs').textContent = currentPairs.length;
            // 更新最快记录显示
            const bestTime = getBestTime(mode);
            document.getElementById('bestTime').textContent = bestTime === Infinity ? '-' : bestTime;
            // 更新当前模式显示
            const modeText = mode === 'fruits' ? '水果模式' : mode === 'animals' ? '动物模式' : '自定义模式';
            document.getElementById('currentMode').textContent = modeText;
            
            // 重置游戏状态
            resetGame();
            
            // 创建卡片
            createCards();
            
            // 显示游戏界面
            customMode.style.display = 'none';
            gameContainer.style.display = 'block';
            
            // 计时器将在第一次翻开卡片时开始
        }

        // 重置游戏状态
        function resetGame() {
            clearInterval(gameTimer);
            gameTimer = null;
            seconds = 0;
            matches = 0;
            flippedCards = [];
            timerDisplay.textContent = '0';
            matchesDisplay.textContent = '0';
            cardGrid.innerHTML = '';
        }

        // 创建卡片
        function createCards() {
            // 创建卡片数组（包含中英文）
            const cards = [...currentPairs.map(pair => pair[0]), ...currentPairs.map(pair => pair[1])];
            
            // 随机打乱卡片
            for (let i = cards.length - 1; i > 0; i--) {
                const j = Math.floor(Math.random() * (i + 1));
                [cards[i], cards[j]] = [cards[j], cards[i]];
            }
            
            // 创建卡片元素
            cards.forEach(text => {
                const card = document.createElement('div');
                card.className = 'card';
                card.dataset.value = text;
                // 添加点击和触摸事件
                const handleInteraction = (e) => {
                    e.preventDefault(); // 阻止默认行为
                    if (!card.classList.contains('processing')) {
                        card.classList.add('processing');
                        flipCard(card);
                        setTimeout(() => card.classList.remove('processing'), 300);
                    }
                };
                card.addEventListener('click', handleInteraction);
                card.addEventListener('touchstart', handleInteraction);
                cardGrid.appendChild(card);
            });
        }

        // 翻转卡片
        function flipCard(card) {
            // 如果卡片已经匹配或已经翻开，则不执行操作
            if (card.classList.contains('matched') || card.classList.contains('flipped') || flippedCards.length >= 2) {
                return;
            }

            // 第一次翻开卡片时开始计时
            if (!gameTimer) {
                startTimer();
            }
            
            // 翻转卡片
            card.classList.add('flipped');
            card.textContent = card.dataset.value;
            flippedCards.push(card);
            
            // 检查是否有两张卡片被翻开
            if (flippedCards.length === 2) {
                checkMatch();
            }
        }

        // 检查匹配
        function checkMatch() {
            const [card1, card2] = flippedCards;
            const value1 = card1.dataset.value;
            const value2 = card2.dataset.value;
            
            // 检查是否匹配（在词对中查找）
            const isMatch = currentPairs.some(pair => 
                (pair[0] === value1 && pair[1] === value2) || 
                (pair[1] === value1 && pair[0] === value2)
            );
            
            setTimeout(() => {
                if (isMatch) {
                    // 匹配成功
                    card1.classList.add('matched');
                    card2.classList.add('matched');
                    matches++;
                    matchesDisplay.textContent = matches;
                    
                    // 检查游戏是否完成
                    if (matches === currentPairs.length) {
                        clearInterval(gameTimer);
                        const isNewRecord = updateBestTime(currentMode, seconds);
                        setTimeout(() => {
                            const bestTime = getBestTime(currentMode);
                            const message = isNewRecord
                                ? `恭喜！你创造了新纪录！用时 ${seconds} 秒完成了游戏！`
                                : `恭喜！你用时 ${seconds} 秒完成了游戏！\n当前最快记录：${bestTime} 秒`;
                            alert(message);
                        }, 300);
                    }
                } else {
                    // 匹配失败，翻回卡片
                    card1.classList.remove('flipped');
                    card2.classList.remove('flipped');
                    card1.textContent = '';
                    card2.textContent = '';
                }
                
                flippedCards = [];
            }, 1000);
        }

        // 开始计时器
        function startTimer() {
            gameTimer = setInterval(() => {
                seconds++;
                timerDisplay.textContent = seconds;
            }, 1000);
        }

        // 自定义模式开始游戏按钮事件
        startCustomGameBtn.addEventListener('click', () => {
            const input = customTextarea.value.trim();
            const pairs = input.split('\n')
                .map(line => line.trim())
                .filter(line => line)
                .map(line => line.split(/\s+/));
            
            if (pairs.length < 4) {
                alert('请至少输入4对中英文对应词！');
                return;
            }
            
            if (pairs.some(pair => pair.length !== 2)) {
                alert('格式错误！请确保每行包含一个中文和一个英文，用空格分隔。');
                return;
            }
            
            addCustomPairs(pairs);
            const pairCount = parseInt(pairCountSelect.value);
            startGame('custom', pairs.slice(0, pairCount));
        });

        // 重新开始按钮事件
        restartGameBtn.addEventListener('click', () => {
            if (currentMode) {
                startGame(currentMode);
            }
        });

        // 词对数量选择事件
        pairCountSelect.addEventListener('change', () => {
            if (currentMode) {
                startGame(currentMode);
            }
        });

        // 加载保存的记录和自定义词对
        loadRecords();
        loadCustomWords();
    </script>
</body>
</html>